package com.Txunda.fxw.base;

import java.io.InterruptedIOException;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.net.UnknownServiceException;
import java.util.Map;


import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.Toast;

import com.lidroid.xutils.ViewUtils;
import com.Txunda.fxw.R;
import com.Txunda.fxw.base.fragment.IBaseFragement;
import com.Txunda.fxw.base.web.ApiListener;
import com.Txunda.fxw.config.WeApplication;
import com.Txunda.fxw.gif.GifImageView;
import com.Txunda.fxw.tipstoast.TipsToast;
import com.umeng.analytics.MobclickAgent;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 主Fragment类，继承此类之后才能使用BaseAty中的与Fragment交互的方法
 *
 * @author Zero
 * <p>
 * 2014年12月19日
 */
public abstract class BaseFragment extends Fragment implements IBaseFragement, ApiListener {

    private FrameLayout content;
    private View progress;
    private View error;
    private ProgressDialog progressDialog;

    protected WeApplication application;

    protected Object mDataIn;
    private boolean isShowContent; // 当出错时标识是否显示错误页面
    protected boolean hasAnimiation = true; // 启动页面时是否带启动动画
    private Unbinder unbinder;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 向用户展示信息前的准备工作在这个方法里处理
        preliminary();
    }


    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View layout = inflater.inflate(R.layout.aty_base, container, false);
        initControls(layout);
        setBasicContentView(getLayoutResId());
		ViewUtils.inject(this, layout);
        unbinder = ButterKnife.bind(this, layout);
        return layout;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // 请求数据
        requestData();
    }

    @Override
    public void onResume() {
        super.onResume();
        showStatus("onResume");
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
    }

    @Override
    public void onComeIn(Object data) {
        mDataIn = data;
        showStatus("onComeIn");
    }

    @Override
    public void onLeave() {
        showStatus("onLeave");
    }

    @Override
    public void onBack(Object data) {
        showStatus("onBack");
    }

    @Override
    public void onStop() {
        super.onStop();
        showStatus("onStop");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }

    private void showStatus(String status) {
        Log.d("test", String.format("%s %s", this.getClass().getName(), status));
    }

    /**
     * 初始化控件
     */
    private void initControls(View layout) {
        content = (FrameLayout) layout.findViewById(R.id.content);
        // 给最底层的layout设置一个点击监听防止切换页面之后还会点击到别的页面的BUG
        content.setOnClickListener(null);
        progress = View.inflate(getActivity(), R.layout.loading_content, null);
        ImageView loading_gifview = (ImageView) progress.findViewById(R.id.loading_gifview);
        error = View.inflate(getActivity(), R.layout.layout_error, null);
        error.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                requestData();
                content.removeView(error);
            }
        });
        progressDialog = new ProgressDialog(getActivity(), R.style.loading_dialog);
        progressDialog.setIndeterminate(true);
        progressDialog.setCancelable(false);
        progressDialog.setCanceledOnTouchOutside(false);
    }

    /**
     * 设置content的子布局
     */
    private void setBasicContentView(int layoutResId) {
        LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(layoutResId, null);
        LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        view.setLayoutParams(layoutParams);
        content.addView(view);
    }

    /**
     * 向用户展示信息前的准备工作在这个方法里处理
     */
    private void preliminary() {
        application = (WeApplication) getActivity().getApplication();
        // 初始化数据
        initialized();
    }

    /**
     * 用于设置页面布局
     */
    protected abstract int getLayoutResId();

    /**
     * 初始化数据
     */
    protected abstract void initialized();

    protected abstract void requestData();

    public BaseActivity getContext() {
        return (BaseActivity) getActivity();
    }

    public void onClick(View v) {
    }

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    }

    // =========================================================== 启动Activity
    // ===========================================================

    /**
     * 启动一个Activity
     *
     * @param className 将要启动的Activity的类名
     * @param options   传到将要启动Activity的Bundle，不传时为null
     */
    protected void startActivity(Class<?> className, Bundle options) {
        Intent intent = new Intent(getActivity(), className);
        if (options != null) {
            intent.putExtras(options);
        }
        startActivity(intent);
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        if (hasAnimiation) {
            getActivity().overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
        }
    }

    // ================ 信息提示方式 ===================

    /**
     * 含有标题、内容和确定按钮的对话框 -- 一般用来显示信息
     *
     * @param title
     * @param message
     */
    protected void showDialog(String title, String message) {
        showDialog(title, message, "确定", null);
    }

    /**
     * 含有标题、内容和一个按钮的对话框
     *
     * @param title
     * @param message
     * @param positiveText
     * @param listener
     */
    protected void showDialog(String title, String message, String positiveText, DialogInterface.OnClickListener listener) {
        new AlertDialog.Builder(getActivity()).setTitle(title).setMessage(message).setPositiveButton(positiveText, listener).create().show();
    }

    /**
     * 含有标题、内容和两个按钮的对话框
     *
     * @param title
     * @param message
     * @param positiveText
     * @param negativeText
     * @param positiveListener
     * @param negativeListener
     */
    protected void showDialog(String title, String message, String positiveText, String negativeText, DialogInterface.OnClickListener positiveListener, DialogInterface.OnClickListener negativeListener) {
        new AlertDialog.Builder(getActivity()).setTitle(title).setMessage(message).setPositiveButton(positiveText, positiveListener).setNegativeButton(negativeText, negativeListener).create().show();
    }

    /**
     * 带有item的Dialog
     *
     * @param title
     * @param itemsId
     * @param listener
     */
    protected void showItemsDialog(String title, int itemsId, DialogInterface.OnClickListener listener) {
        new AlertDialog.Builder(getActivity()).setTitle(title).setItems(itemsId, listener).show();
    }

    /**
     * 带有item的Dialog
     *
     * @param title
     * @param itemsId
     * @param listener
     */
    protected void showItemsDialog(String title, CharSequence[] items, DialogInterface.OnClickListener listener) {
        new AlertDialog.Builder(getActivity()).setTitle(title).setItems(items, listener).show();
    }

    protected void showToast(String text) {
        Toast toast = Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.setText(text);
        toast.show();
    }


    /**
     * 自定义toast
     *
     * @param iconResId
     * 图片
     * @param msgResId
     * 提示文字
     */
    private TipsToast tipsToast;

    protected void showTips(int iconResId, String tips) {
        if (tipsToast != null) {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                tipsToast.cancel();
            }
        } else {
            tipsToast = TipsToast.makeText(getActivity(), tips,
                    TipsToast.LENGTH_SHORT);
        }
        tipsToast.show();
        tipsToast.setIcon(iconResId);
        tipsToast.setText(tips);
    }

    // ===================== 加载条 ==================

    private boolean isShowing = false;

    protected void showProgressContent() {
        isShowContent = true;
        isShowing = true;
        content.addView(progress);
    }

    protected void removeProgressContent() {
        if (isShowing) {
            isShowing = false;
            content.removeView(progress);
        }
    }

    protected void showProgressDialog() {
        try {
            isShowContent = false;
            if (!progressDialog.isShowing()) {
                progressDialog.show();
                progressDialog.setContentView(R.layout.loading_dialog);
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
        }

    }

    protected void showProgressDialog(String title) {
        isShowContent = false;
        if (!progressDialog.isShowing()) {
            progressDialog.show();
            View views = LayoutInflater.from(getActivity()).inflate(R.layout.loading_dialog, null);
            TextView loading_tv_content = (TextView) views.findViewById(R.id.loading_tv_content);
            loading_tv_content.setText(title);
            progressDialog.setContentView(views);
        }
    }

    protected void removeProgressDialog() {
        try {
            if (progressDialog.isShowing()) {
                progressDialog.dismiss();
            }
        } catch (NullPointerException e) {
            // TODO: handle exception
        }

    }

    // =========================================================== API回调方法
    // ===========================================================

    @Override
    public void onStarted() {
    }

    @Override
    public void onCancelled() {
        removeProgressContent();
        removeProgressDialog();
    }

    @Override
    public void onComplete(String requestUrl, String jsonStr) {
        removeProgressContent();
        removeProgressDialog();
    }

    @Override
    public void onError(String requestUrl, Map<String, String> error) {
        showTips(R.drawable.error, error.get("message"));
        removeProgressContent();
        removeProgressDialog();
    }

    @Override
    public void onException(Exception exception) {
        if (isShowContent) {
            content.addView(error);
        } else {
            if (exception instanceof SocketException || exception instanceof InterruptedIOException || exception instanceof UnknownHostException || exception instanceof UnknownServiceException) {
                showToast(getString(R.string.network_anomaly));
            } else {
                showToast(getString(R.string.server_unknow_error));
            }
        }
        exception.printStackTrace();
        removeProgressContent();
        removeProgressDialog();
    }

    @Override
    public void onLoading(long total, long current, boolean isUploading) {

    }

}
